package net.vsame.url2sql.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 * 公共类
 * 
 * 2011-10-24 下午09:02:16
 * @author <a href="mailto:gaollg@sina.com">Gaollg</a>
 */
public final class FileUtils {
	
	private FileUtils(){}
	
	/**
	 * 取得文件的所有文本内容 
	 * @param file
	 * @return
	 */
	public static String readAllText(File file, Charset charset){
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			return readAllText(fis, charset);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} finally{
			try {
				fis.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 取得文件的所有文本内容 
	 * @param file
	 * @return
	 */
	public static String readAllText(InputStream in, Charset charset){
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
		try {
			String tempString = null;
			while ((tempString = br.readLine()) != null) {
				sb.append(tempString).append("\r\n");
            }
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
	public static String readEndBody(InputStream inputStream, Charset charset){
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(inputStream, charset));
			String tempString = null;
			while ((tempString = br.readLine()) != null) {
				int endIndex = tempString.indexOf("</body>");
				if(endIndex != -1){
					sb.append(tempString.substring(0,endIndex)).append("</body>");
					break;
				}
				sb.append(tempString).append("\r\n");
            }
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * 取得文件的所有文本内容 
	 * @param file
	 * @return
	 */
	public static void writeAllText(String filepathname, String str){
		File file = new File(filepathname);
		File parent = file.getParentFile();
		if(!parent.exists()){
			parent.mkdirs();
		}
		PrintWriter out = null;
		try {
			out= new PrintWriter(file);
			out.print(str);
			out.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally{
			if(out != null){
				out.close();
			}
		}
	}
	
	 // 复制文件
    public static void copyFile(File sourceFile, File targetFile) {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        }catch (Exception e) {
        	throw new RuntimeException(e);
		} finally {
            // 关闭流
            if (inBuff != null){
            	try {
					inBuff.close();
				} catch (IOException e) {
				}
            }
            if (outBuff != null){
            	try {
					outBuff.close();
				} catch (IOException e) {
				}
            }
        }
    }
    
    public static void copyFile(String source, String target){
    	copyFile(new File(source), new File(target));
    }
	
	public static void main(String[] args) {
		copyFile("/home/gaolei/question/aaa.gif", "/home/gaolei/question/b.gif");
	}
	
	
	/**
	 * GET请求 默认是 utf-8 编码
	 * @param url
	 * @param params
	 * @return
	 */
	public static String get(String url){
		return get(url, Charset.forName("utf-8"));
	}

	/**
	 * GET请求
	 * @param url 请求URL
	 * @return 
	 */
	public static String get(String url, Charset charset) {
		String result = "";
		InputStream in = null;
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.connect();
			in = conn.getInputStream();
			
			byte[] bytes = new byte[1024];
			int length = -1;
			StringBuffer sb = new StringBuffer();
			while ((length = in.read(bytes)) != -1) {
				sb.append(new String(bytes, 0, length, charset));
			}
			result = sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		return result;
	}
	
}
